package cn.myspringboot.system.service.impl;

import cn.myspringboot.base.service.impl.BaseServiceImpl;
import cn.myspringboot.system.mapper.EmployeeMapper;
import cn.myspringboot.system.mapper.RoleMapper;
import cn.myspringboot.system.service.EmployeeService;
import cn.myspringboot.system.service.RoleService;
import cn.myspringboot.user.domain.Employee;
import cn.myspringboot.user.domain.Role;
import cn.myspringboot.user.query.EmployeeQuery;
import cn.myspringboot.user.query.RoleQuery;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public List<Role> selectRolePage(RoleQuery query) {
        List<Role> roles = roleMapper.selectRolePage(query);
        for (Role role : roles) {
            role.setMenus(roleMapper.selectMenuIdList(role.getId()));
            role.setPermissions(roleMapper.selectPermissionIdList(role.getId()));
        }
        return roles;
    }

    @Override
    @Transactional
    public void add(Role role) {
        Role role1 = roleMapper.fingRole(role);
        if(role1 == null){
            roleMapper.add(role);
        }else {
            throw new RuntimeException(role.getSn()+":该角色编码已存在");
        }
        //保存权限和菜单
        if(role.getPermissions().size()>0){
            roleMapper.addRolePermission(role.getId(),role.getPermissions());
        }
        if(role.getMenus().size()>0){
            roleMapper.addRoleMenu(role.getId(),role.getMenus());
        }
    }

    @Override
    @Transactional
    public void update(Role role) {
        Role role1 = roleMapper.fingRole(role);
        if (role1 != null) {
            throw new RuntimeException(role.getSn()+"该角色已存在");
        }else {
            super.update(role);
        }
        roleMapper.deletePreByRoleId(role.getId());
        if(role.getPermissions().size()>0){
            roleMapper.addRolePermission(role.getId(),role.getPermissions());
        }
        roleMapper.deleteMenuByRoleId(role.getId());
        if(role.getMenus().size()>0){
            roleMapper.addRoleMenu(role.getId(),role.getMenus());
        }
    }

    @Override
    @Transactional
    public void delete(Long id) {
        roleMapper.deletePreByRoleId(id);
        roleMapper.deleteMenuByRoleId(id);
        super.delete(id);
    }

    @Override
    @Transactional
    public void batchDelete(List<Long> ids) {
        super.batchDelete(ids);
    }
}
